package com.fashion.service;

import com.fashion.dao.UserDao;
import com.fashion.exceptions.AdminException;
import com.fashion.model.Administrator;
import com.fashion.utils.ConstItem;
import com.fashion.utils.ManagementUtils;
import com.fashion.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: juventus
 * Date: 11-7-17
 * Time: 下午12:49
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    private UserDao userDao;

    @Override
    public Administrator validateLogin(String userName, String password) {
        if (StringUtils.isNullOrEmpty(userName) || StringUtils.isNullOrEmpty(password)) {
            return null;
        }

        password = ManagementUtils.encryptWithMD5(ConstItem.PASSWORD_PREFIX + password + ConstItem.PASSWORD_SUFFIX);

        String hql = "from Administrator a where a.name=:name and a.password=:password";

        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("name", userName);
        parameters.put("password", password);

        List<Administrator> administratorList = userDao.findItems(hql, parameters);

        if (administratorList.size() == 0) {
            return null;
        }

        return administratorList.get(0);
    }

    @Override
    public List<Administrator> fetchAllAdmins(int page, int rows) {
        String hql = "from Administrator";

        return userDao.findItemsWithPage(hql, new HashMap<String, Object>(), page, rows);
    }

    @Override
    public int countAllAdmins() {
        String hql = "select count(id) from Administrator";

        return userDao.countItems(hql, new HashMap<String, Object>());
    }

    @Override
    public void saveOrUpdate(Object object) {
        userDao.saveOrUpdate(object);
    }

    @Override
    public void deleteEntityById(String id) {
        if(StringUtils.isNullOrEmpty(id)){
            throw new AdminException("The userId to delete should not be null or empty!");
        }

        userDao.deleteById(id, Administrator.class);
    }

    @Override
    public void deleteEntity(Object object) {
        userDao.delete(object);
    }

    @Resource(name = "userDao")
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}
